Ext.define('component.repairData.signeAmount', {
	extend : 'Ext.window.Window',
	callbackFun: function (record) {
		Ext.Msg.alert('提示', '回调函数未配置！');
	},
	config: {
		roomName: '',
		customerName: '',
		signAmount: '',
		paymentMethod: '',
		signedId: ''
	},
	initComponent : function() {
		var me = this;
		var paymentMethodValue = this.paymentMethod;
		var signAmountValue = this.signAmount;
		var signedIdValue = this.signedId;
		var customerName=this.customerName;
		var roomName=this.roomName;
		var paymentMethodsStore = Ext.create("Ext.data.Store", {
			fields: ["value","name"],
	        pageSize: 10,  //页容量5条数据
	        //是否在服务端排序 （true的话，在客户端就不能排序）
	        remoteSort: false,
	        proxy: {
	            type: 'ajax',
	            url: contextPath + "/marketing/changecontact/getPaymentMethod",
	            reader: {
	                type: 'json',
	                root: 'obj',
	                totalProperty: 'total'
	            }
	        },
	        autoLoad: true  //即时加载数据
		});
		
		Ext.define('ccNeedReceiveRecord', { 
            extend: 'Ext.data.Model', 
            fields: ["receivablesFunds","totalReceivablesAmount","receivablesDate","orgName","agentName","haveReceivedTotal","unReceivedTotal","businessFlag","housingFundType"]
	    });
		
		var ccGridStore = Ext.create('Ext.data.Store', {
			model:'ccNeedReceiveRecord',
			//加载签约待收款记录
	        fields: ["receivablesFunds","totalReceivablesAmount","receivablesDate", "orgName", "agentName","haveReceivedTotal","unReceivedTotal"],
	        pageSize: 10,  //页容量5条数据
	        //是否在服务端排序 （true的话，在客户端就不能排序）
	        remoteSort: false,
	        proxy: {
	            type: 'ajax',
	            url: contextPath+'/marketing/proceeds/needList',
	            reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
	                type: 'json', //返回数据类型为json格式
	                root: 'rows',  //数据
	                totalProperty: 'total' //数据总条数
	            },
	            actionMethods: {read: 'POST'},
	            extraParams:{
	            	relationId:signedIdValue,
	            	businessType:'2'
	            }
	        },
	        autoLoad: true  //即时加载数据
		});
		
		var newCcGridStore = Ext.create('Ext.data.Store', {
			model:'ccNeedReceiveRecord',
			//加载签约待收款记录
	        fields: ["receivablesFunds","totalReceivablesAmount","receivablesDate", "orgName", "agentName","haveReceivedTotal","unReceivedTotal"]
		});
		
		var columns = [{
			text : "款项",
			dataIndex : 'receivablesFunds',
			width:'15%'
		}, {
			text : "应收金额",
			dataIndex : 'totalReceivablesAmount',
			width:'15%'
		}, {
			text : "应收日期",
			dataIndex : 'receivablesDate',
			width:'15%',
            renderer: function(value,metadata,record){  
                if(value!=null && value!=""){
                	return Ext.Date.format(new Date(value),'Y-m-d');
                }
                return value;
            }
		}, {
			text : "银行单位",
			dataIndex : 'orgName',
			width:'15%'
		}, {
			text : "经办人",
			dataIndex : 'agentName',
			width:'10%'
		},
		{text: '已收金额', dataIndex: 'haveReceivedTotal',width:'15%'},
        {text: '未收金额', dataIndex: 'unReceivedTotal',width:'15%'}
        ];
		
		var oldNeedPayGrid=Ext.create('Ext.grid.Panel', {
			title:"原收款信息",
			margin: "10 0 0 0",
			autoHeight: true,
			autoWidth: true,
			columnLines: true,
	        viewConfig: {
	            stripeRows: true
	        },
			store : ccGridStore,
			columns : columns
		});
		
		
		var columns_1 = [{
			text : "款项",
			dataIndex : 'receivablesFunds',
			width:'20%'
		}, {
			text : "应收金额",
			dataIndex : 'totalReceivablesAmount',
			width:'15%',
			editor: {
                xtype: 'numberfield',
                allowBlank: false,
                hideTrigger:true,
                minValue: 1
            }
		}, {
			text : "应收日期",
			dataIndex : 'receivablesDate',
			width:'20%',
			editor: {
                xtype: 'datefield',
                format: 'Y-m-d',
                allowBlank: false
            },
            renderer: function(value,metadata,record){  
                if(value!=null && value!=""){
                	return Ext.Date.format(new Date(value),'Y-m-d');
                }
                return value;
            }
		}, {
			text : "银行单位",
			dataIndex : 'orgName',
			width:'20%',
			editor: {
                xtype: 'textfield'
            }
		}, {
			text : "经办人",
			dataIndex : 'agentName',
			width:'20%',
			editor: {
                xtype: 'textfield'
            }
		}
        ];
		var ccCellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
	        clicksToEdit: 1
	    });
		
		var newNeedPayGrid=Ext.create('Ext.grid.Panel', {
			title:"应收款信息",
			margin: "10 0 0 0",
			autoHeight: true,
			autoWidth: true,
			columnLines: true,
	        viewConfig: {
	            stripeRows: true
	        },
			store : newCcGridStore,
			columns : columns_1,
			plugins: [ccCellEditing],
			listeners:{
				'edit':function(editor, e){
		    		var record = e.record;
	        		var editorField=editor.context.field;
	        		if(editorField=="totalReceivablesAmount"){
	        			var totalReceivablesAmount = 0; 
	        	        for(var i=0, len=newCcGridStore.data.length; i<len; i++){
	        				var data = newCcGridStore.getAt(i).data;
	        				if(null!=data.totalReceivablesAmount && data.totalReceivablesAmount!=""){
	        					totalReceivablesAmount += parseFloat(data.totalReceivablesAmount)
	        				}
	        			}
	        	        var showAmount="<font style=\"color: red; font-size: 20px;\">【"+Ext.util.Format.number(totalReceivablesAmount, "0,000.00")+"】</font>元";
	        	        Ext.getCmp("newSigneAmount").setValue(showAmount);
	        	        
	        		}
				} 
			}
		});
		
		var contactchangeForm = Ext.create('Ext.form.FormPanel', {
		    items: [
		    	{xtype: "displayfield", value: "<h3 style=\"color: red;\">(注:此功能可用于变更签约合同金额、付款方式、应收款项信息，保存后合同金额、付款方式、应收款信息会被修改，操作成功请重新进行收款。)</h3>"},
		    	{xtype: "displayfield", fieldLabel: '客户', value: customerName},
		    	{xtype: "displayfield", fieldLabel: '房号', value: roomName},
		    	{xtype: "displayfield", fieldLabel: '合同金额(元)', value: Ext.util.Format.number(signAmountValue, "0,000.00")},
		    	{
	    			xtype: 'combobox',
		            fieldLabel: '原收款方式',
		            name:'paymentMethod',
		            store: paymentMethodsStore,
		            queryMode: 'local',
		            displayField: 'name',
		            readOnly:true,
		            valueField: 'value',
			            listeners: {
			            	afterRender: function(combo) {
						         if(paymentMethodValue){
							         combo.setValue(paymentMethodValue);
						         }
					      	}
			            }
		            },
		    	oldNeedPayGrid
		    ]
		});
		
		var newContactchangeForm = Ext.create('Ext.form.FormPanel', {
		    items: [
	            {xtype: "displayfield", id:"newSigneAmount",fieldLabel: '新合同金额(元)',value: ""},
	            {
	    			xtype: 'combobox',
		            fieldLabel: '新收款方式',
		            name:'paymentMethod',
		            store: paymentMethodsStore,
		            queryMode: 'local',
		            displayField: 'name',
		            valueField: 'value',
			            listeners: {
			                change: function(field,value) {
			                	newCcGridStore.removeAll();
			                    if(value=="1"){ 
			                    	//一次性付款 
			                    	var record  = new ccNeedReceiveRecord({
			                    		receivablesFunds:field.getRawValue(),
			                    		businessFlag:'9',
			                    		housingFundType:'5'
			                    	});
			                    	newCcGridStore.insert(0, record);
			                    }else if(value=="2"){
			                    	//分期付款
			                    	var record_1  = new ccNeedReceiveRecord({
			                    		receivablesFunds:'一期款',
			                    		businessFlag:'9',
			                    		housingFundType:'12'
			                    	});
			                    	var record_2  = new ccNeedReceiveRecord({
			                    		receivablesFunds:'二期款',
			                    		businessFlag:'9',
			                    		housingFundType:'13'
			                    	});
			                    	var record_3  = new ccNeedReceiveRecord({
			                    		receivablesFunds:'三期款',
			                    		businessFlag:'9',
			                    		housingFundType:'14'
			                    	});
			                    	var record_4  = new ccNeedReceiveRecord({
			                    		receivablesFunds:'四期款',
			                    		businessFlag:'9',
			                    		housingFundType:'15'
			                    	});
			                    	var record_5  = new ccNeedReceiveRecord({
			                    		receivablesFunds:'五期款',
			                    		businessFlag:'9',
			                    		housingFundType:'16'
			                    	});
			                    	newCcGridStore.insert(0, record_1);
			                    	newCcGridStore.insert(1, record_2);
			                    	newCcGridStore.insert(2, record_3);
			                    	newCcGridStore.insert(3, record_4);
			                    	newCcGridStore.insert(4, record_5);
			                    }else if(value=="3"){
			                    	//商业按揭
			                    	var record_1  = new ccNeedReceiveRecord({
			                    		receivablesFunds:'首付款',
			                    		businessFlag:'9',
			                    		housingFundType:'6'
			                    	});
			                    	var record_2  = new ccNeedReceiveRecord({
			                    		receivablesFunds:'按揭银行',
			                    		businessFlag:'9',
			                    		housingFundType:'7'
			                    	});
			                    	newCcGridStore.insert(0, record_1);
			                    	newCcGridStore.insert(1, record_2);
			                    }else if(value=="4"){
			                    	//公积金按揭
			                    	var record_1  = new ccNeedReceiveRecord({
			                    		receivablesFunds:'首付款',
			                    		businessFlag:'9',
			                    		housingFundType:'10'
			                    	});
			                    	var record_2  = new ccNeedReceiveRecord({
			                    		receivablesFunds:'公积金',
			                    		businessFlag:'9',
			                    		housingFundType:'11'
			                    	});
			                    	newCcGridStore.insert(0, record_1);
			                    	newCcGridStore.insert(1, record_2);
			                    }else if(value=="5"){
			                    	//组合贷款
			                    	var record_1  = new ccNeedReceiveRecord({
			                    		receivablesFunds:'首付款',
			                    		businessFlag:'9',
			                    		housingFundType:'17'
			                    	});
			                    	var record_2  = new ccNeedReceiveRecord({
			                    		receivablesFunds:'按揭银行',
			                    		businessFlag:'9',
			                    		housingFundType:'18'
			                    	});
			                    	var record_3  = new ccNeedReceiveRecord({
			                    		receivablesFunds:'公积金',
			                    		businessFlag:'9',
			                    		housingFundType:'19'
			                    	});
			                    	newCcGridStore.insert(0, record_1);
			                    	newCcGridStore.insert(1, record_2);
			                    	newCcGridStore.insert(2, record_3);
			                    }
			                }
			            }
		            },
		            newNeedPayGrid]
		});

		var mainPanel=Ext.create('Ext.form.Panel', {
		    items:[contactchangeForm,newContactchangeForm],
		    buttons: [
				{
					xtype: "button",
					text : "保存",
					name: "btn_saveChange",
					icon : contextPath + '/resources/ExtJSicons/database_add.png',
					listeners: {
						click: function(){
						    Ext.MessageBox.confirm("提示","是否变更合同信息?",function(btn,txt){
						    	if(btn != "yes"){
						    		return false;
						    	}

						    	// 发送请求
								var totalMoney = 0;
								var jsonArray=[];
								//判断应收款信息是否填写正确
								var flag = true;
								var length = newNeedPayGrid.getStore().data.length;
								for(var i = (length - 1); i >= 0; i--){
									var record = newNeedPayGrid.getStore().data.items[i];
									var totalReceivablesAmount = record.data["totalReceivablesAmount"];
				                	if(totalReceivablesAmount){
				                		totalMoney += totalReceivablesAmount;
				                		flag = false;
				                	}else if(!flag){
				                		jsonArray = [];
					                	Ext.Msg.alert('提示', '请检查输入的应收金额。');
					                    return false;
				                	}
				                	var receivablesDate = record.data["receivablesDate"];
				                	if(receivablesDate){
				                		flag = false;
				                	}else if(!flag){
				                		jsonArray = [];
					                	Ext.Msg.alert('提示', '请检查输入的应收日期。');
					                    return false;
				                	}
					                jsonArray.push(Ext.JSON.encode(record.data));
								}
								if(jsonArray.length <= 0){
									Ext.Msg.alert('提示', '请填写应收款');
									return false;
								}
								//组装新应收款信息
								jsonArray=[];
								newNeedPayGrid.getStore().each(function(record){
									var totalReceivablesAmount = record.data["totalReceivablesAmount"];
									var receivablesDate = record.data["receivablesDate"];
									//过滤为空的数据
									if(!totalReceivablesAmount){
										return false;
									}
									jsonArray.push(Ext.JSON.encode(record.data));
								});
								console.log(jsonArray);
								var resultJson=Ext.JSON.encode(jsonArray);
								if(jsonArray.length > 0){
									var waiting = Ext.Msg.wait('正在处理，请稍等...','','');
							    	Ext.Ajax.request({
										method: "POST",
										url: contextPath + "/marketing/changecontact/signeRepairData",
										params:{
											params: resultJson,
											signedId: signedIdValue,
											paymentMethod: newContactchangeForm.getForm().findField("paymentMethod").getValue()
										},
										success: function(response, options){
											if(waiting != null){
												waiting.hide();
											}
											var jsonResult = Ext.decode(response.responseText);
											if(jsonResult.res == 1){
												Ext.MessageBox.confirm("提示",jsonResult.resMsg,function(btn,txt){
												    	if(btn=="yes"){
												    		me.close();
												    		me.callbackFun();
												    	}
												})
											}else{
												Ext.Msg.alert('失败', jsonResult.resMsg);
											}
										},
										failure: function(response, options){
											Ext.Msg.alert('错误', '请求超时.');
										}
									});
								}
						    });
						}
					}
				},
				{
					xtype: "button",
					text : "取消",
					id: "btn_back",
					name: "btn_back",
					icon : contextPath + '/resources/ExtJSicons/shape_move_backwards.png',
					listeners: {
						click: function(){
							me.close();
						}
					}
				}
			]
		});
		
		var defaultConfig = {
			frame:true,
			title : '合同信息变更',
			width : 700,
			height : 580,
			autoHeight: true,
			items:[mainPanel]
		};
		Ext.apply(this,defaultConfig);
		this.callParent();
	}
});
